package com.vehicle.exception;

import com.vehicle.domains.vo.Result;
import com.vehicle.enums.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result<Void> dataIntegrityViolationExceptionHandler(DataIntegrityViolationException ex) {
        log.error("数据长度异常:", ex);
        return Result.error(StatusCode.PARAMS_ERROR.getCode(), "参数异常"+ex.getMessage());
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Void> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException ex) {
        log.error("请求体解析异常:", ex);

        // 提取核心错误信息（简化版，可根据实际需求优化）
        String message = "请求参数格式错误，请检查JSON格式或数据类型";
        if (ex.getCause() != null) {
            String causeMsg = ex.getCause().getMessage();
            // 例如：Jackson解析错误时，提取关键信息
            if (causeMsg.contains("Cannot deserialize value of type")) {
                message = "参数类型不匹配：" + causeMsg.substring(0, Math.min(causeMsg.length(), 100));
            } else if (causeMsg.contains("Unexpected character")) {
                message = "JSON格式错误：" + causeMsg.substring(0, Math.min(causeMsg.length(), 50));
            }
        }

        return Result.error(StatusCode.PARAMS_ERROR.getCode(), message);
    }
    @ExceptionHandler(VehicleAccessException.class)
    public Result<Void> vehicleAccessExceptionHandler(VehicleAccessException e) {
        log.error("出现业务异常", e);
        return Result.error(e.getDefineCode(), e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 存储错误字段和对应信息的Map
        Map<String, String> errorMap = new HashMap<>();

        // 遍历所有校验失败的字段
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            String fieldName = fieldError.getField(); // 错误的字段名（如username、phone）
            String errorMsg = fieldError.getDefaultMessage(); // 错误信息（如"用户名不能为空"）
            errorMap.put(fieldName, errorMsg);
        }
        return Result.error(StatusCode.PARAMS_ERROR.getCode(),StatusCode.PARAMS_ERROR.getMessage()+errorMap);
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> exceptionHandler(Exception e) {
        log.error("出现系统异常", e);
        return Result.error(StatusCode.SYSTEM_ERROR.getCode(), StatusCode.SYSTEM_ERROR.getMessage());
    }
}
